﻿using System;
using System.Xml;

using CommunityServer.Components;

namespace CSLive.LiveSettings
{
    public static class LiveSettingDataManager
    {
        public static T Get<T>() where T : class, new()
        {
            return CSCache<T>.Get("CSLiveData", 20000, 20000, delegate
                                                                     {
                                                                         string xml = LiveSettings.Instance().GetLiveSettingsXML();
                                                                         T local;
                                                                         try
                                                                         {
                                                                             local = Serializer.ConvertToObject(xml, typeof(T)) as T;
                                                                             if (local == null)
                                                                             {
                                                                                 local = Activator.CreateInstance<T>();
                                                                             }
                                                                         }
                                                                         catch (Exception exception)
                                                                         {
                                                                             if (exception.InnerException is XmlException)
                                                                             {
                                                                                 throw new CSException(CSExceptionType.SiteSettingsInvalidXML, "Custom Settings XML is invalid");
                                                                             }

                                                                             throw;
                                                                         }

                                                                         if (local == null)
                                                                         {
                                                                             local = Activator.CreateInstance<T>();
                                                                         }

                                                                         return local;
                                                                     });
        }

        public static void Update(LiveSettingData siteData)
        {
            LiveSettings.Instance().SaveLiveSettings(Serializer.ConvertToString(siteData));
        }
    }
}